﻿/*
 * Author: .net follower (http://dotnetfollower.com)
 * Copyright: � 2012 .net follower 
 * Usage: software is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using WebLoading;

namespace TestApp
{
    public class GeoNamesCitiesLoader : JsonLoader<List<GeoNamesCitiesLoader.City>>
    {
        public class City
        {
            public string  FCodeName   { get; set; }
            public string  ToponymName { get; set; }
            public string  CountryCode { get; set; }
            public string  Name        { get; set; }
            public string  Wikipedia   { get; set; }
            public decimal Population  { get; set; }
            public double  Longitude   { get; set; }
            public double  Latitude    { get; set; }            
        }

        protected override bool IsRawDataValid(Dictionary<string, object> rawData)
        {
            return base.IsRawDataValid(rawData);
        }

        protected override string PrepareUrl()
        {
            return "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";
        }

        protected override List<City> ParseData(Dictionary<string, object> rawData)
        {
            List<City> res = new List<City>();

            IEnumerable arrayOfDictionaries = SelectObject(rawData, "geonames") as IEnumerable;
            foreach (Dictionary<string, object> dict in arrayOfDictionaries)
                res.Add(CreateCity(dict));

            return res;
        }
       
        private City CreateCity(Dictionary<string, object> metadata)
        {
            City res = new City();

            foreach (KeyValuePair<string, object> pair in metadata)
            {
                switch (pair.Key.ToLower())
                {
                    case "fcodename":   res.FCodeName   = Convert.ToString(pair.Value);  break;
                    case "toponymname": res.ToponymName = Convert.ToString(pair.Value);  break;
                    case "countrycode": res.CountryCode = Convert.ToString(pair.Value);  break;
                    case "name":        res.Name        = Convert.ToString(pair.Value);  break;
                    case "wikipedia":   res.Wikipedia   = Convert.ToString(pair.Value);  break;
                    case "lng":         res.Longitude   = Convert.ToDouble(pair.Value);  break;
                    case "lat":         res.Latitude    = Convert.ToDouble(pair.Value);  break;
                    case "population":  res.Population  = Convert.ToDecimal(pair.Value); break;                    
                }
            }            

            return res;
        }
    }
}
